<?php
require '../$header.php';
require '../$enforce_login.php';

$return = array();
$error = false;

$SpotID = $DB->escapeInt($_POST['SpotID']);
$Vote = $DB->escapeInt($_POST['Vote']);
$Vote = ($Vote == "1" ? 1 : 0);

//make sure the spot id exists
$DB->query("
	SELECT NULL
	FROM spot
	WHERE ID = '{$SpotID}'
	LIMIT 1");

if($DB->num() != 1)
{
	$return['Error'] = "This Spot Doesn't Exist!";
	$error = true;
}

//make sure they haven't already voted
if(!$error)
{
	$DB->query("
		SELECT NULL 
		FROM spotvotes 
		WHERE UserID = '{$UserID}' 
		AND SpotID = '{$SpotID}' 
		LIMIT 1
	");
	
	if($DB->num() != 0)
	{
		$return['Error'] = "You've Already Voted on this Spot";
		$error = true;
	}
}


//count their vote
if(!$error)
{
	//was this an up vote?
	if($Vote == 1)
	{
		$DB->query("
			UPDATE spot
			SET UpVotes = UpVotes+1
			WHERE ID = '{$SpotID}'
			LIMIT 1
		");
	}
	else
	{
		$DB->query("
			UPDATE spot
			SET DownVotes = DownVotes+1
			WHERE ID = '{$SpotID}'
			LIMIT 1
		");
	}
	
	$DB->query("
		INSERT INTO spotvotes
		(
			SpotID,
			UserID,
			UpDown
		)
		VALUES
		(
			'{$SpotID}',
			'{$UserID}',
			'{$Vote}'
		)
	");
	
	$SpotVoteID = $DB->getInsertID();
	
	$DB->query("SELECT * FROM spot WHERE ID='{$SpotID}' LIMIT 1");
	
	if($DB->num() == 1)
	{
		$fetch = $DB->fetch();
		$return = $fetch;
	}
	else
	{
		$return['Error'] = "Could not find spot vote!";
	}
}

echo json_encode($return);

require '../$footer.php';
?>